#!/bin/sh
#name seerver_moniter.sh
formatday=`date +"%Y-%m-%d %H:%M:%S"`
report=/data/console/zplay/monitor/server_monitor.log
mails=$1
mem_quota=80
hd_quota=80
cpu_quota=80
ip=10.171.62.27

# watch memory usage
watch_mem()
{
	memtotal=`cat /proc/meminfo |grep "MemTotal"|awk '{print $2}'`
	memfree=`cat /proc/meminfo |grep "MemFree"|awk '{print $2}'`
	cached=`cat /proc/meminfo |grep "^Cached"|awk '{print $2}'`
	buffers=`cat /proc/meminfo |grep "Buffers"|awk '{print $2}'`

	mem_usage=$((100-memfree*100/memtotal-buffers*100/memtotal-cached*100/memtotal))
	if [ $mem_usage -gt $mem_quota ];then
		mem_message="WARN! The Memory usage is over than $mem_usage%"
		return 1
	else
		return 0
	fi
}

# watch disk usage
watch_hd()
{
	sda1_usage=`df -h|grep '493G'|awk '{print $4}'|sed 's/%//G'`
	if [ $sda1_usage -gt $hd_quota ]; then
		hd_message="WARN! The Hard Disk usage is over than $hd_quota%"
		return 1
	else
		return 0
	fi
}

# watch cpu usage in one minute
get_cpu_info()
{
	cat /proc/stat|grep '^cpu[0-9]'|awk '{used+=$2+$3+$4;unused+=$5+$6+$7+$8} END{print used,unused}'
}

watch_cpu()
{
	time_point_1=`get_cpu_info`
	sleep 60
	time_point_2=`get_cpu_info`
	cpu_usage=`echo $time_point_1 $time_point_2|awk '{used=$3-$1;total=$3+$4-$1-$2;print used*100/total}'`
	if [[ $cpu_usage > $cpu_quota ]]; then
		cpu_message="WARN! The CPU Usage is over than $cpu_quota%"
		return 1
	else
		return 0
	fi
}

proc_cpu_top10()
{
	proc_busiest=`ps aux|sort -nk3r|head -n 11`
}

watch_mem
if [ $? -eq 1 ]; then
	echo "$formatday    $mem_message" >> $report
fi

watch_hd
if [ $? -eq 1 ]; then
	date >> $report
echo "$hd_message" >> $report
fi

watch_cpu
if [ $? -eq 1 ]; then
	echo "formatday    $cpu_message" >> $report
	proc_cpu_top10
	echo "$proc_busiest" >> $report
fi

if [ -a $report ]; then
	cat $report | mail -s "$ip CUP/MEM/DISK Stat of Alarm" $mails
	rm -rf $report
fi
